package com.shundr.shipper;

import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult.AddressComponent;
import com.shundr.shipper.base.BaseFragment;
import com.shundr.shipper.cargo.CargoListActivity;
import com.shundr.shipper.common.AreaGridActivity;
import com.shundr.shipper.common.model.AreaInfo;
import com.shundr.shipper.common.util.AreaUtils;
import com.shundr.shipper.common.util.BaiduMapManager;
import com.shundr.shipper.common.util.JsonUtil;
import com.shundr.shipper.common.util.PrefConstants;
import com.shundr.shipper.common.util.PrefUtils;
import com.shundr.shipper.common.util.ToastHelper;
import com.shundr.shipper.frame.constant.LContext;
import com.shundr.shipper.frame.util.LLogger;
import com.shundr.shipper.frame.util.StringUtil;
import com.shundr.shipper.truck.SearchTruckListActivity;

/**
 * 查找货源的界面
 * SearchCargoFragment
 * 
 * @author larry 2015-4-13 上午10:50:55 
 * @version 1.0.0
 *
 */
public class SearchCargoFragment extends BaseFragment implements
		OnClickListener {

	private TextView tvStart;
	private TextView tvEnd;
	private Button btnSearch;
	private Button btnSwitch;
	
	private BaiduMapManager mMapManager;
	private ImageView ivImage;
	
	private String startCode = LContext.nullStr;
	private String endCode = LContext.nullStr;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_search, null);//
		ivImage=(ImageView)view.findViewById(R.id.iv_search_cargo_image);
		tvStart = (TextView) view.findViewById(R.id.tv_start);
		tvEnd = (TextView) view.findViewById(R.id.tv_end);
		tvEnd.setText("全国");
		btnSearch = (Button) view.findViewById(R.id.btn_search);
		btnSwitch = (Button) view.findViewById(R.id.btn_switch);
		btnSwitch.setOnClickListener(this);
		tvStart.setOnClickListener(this);
		tvEnd.setOnClickListener(this);
		btnSearch.setOnClickListener(this);
		view.findViewById(R.id.btn_search_truck).setOnClickListener(this);
		
		String srcPlace=PrefUtils.getPrefString(getActivity(), PrefConstants.SRC_PLACE, "全国");
		startCode=PrefUtils.getPrefString(getActivity(), PrefConstants.SRC_CODE,startCode);
		tvStart.setText(srcPlace);
		return view;

	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		mMapManager = new BaiduMapManager(mContext, null);
		mMapManager.initMap();
		mMapManager.setLocationListener(new MyLocationListenner());
		mMapManager.startLocation();
	}
	
	@Override
	public void onPause() {
		mMapManager.stop();
		super.onPause();
	}

	@Override
	public void onResume() {
		//mMapManager.resume();
		super.onResume();
	}

	@Override
	public void onDestroy() {
		mMapManager.destroy();
		releaseImageView(ivImage);
		super.onDestroy();
	}
	
	private boolean isFirstLoc = true;// 是否首次定位
	/**
	 * 定位SDK监听函数
	 */
	public class MyLocationListenner implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {
			// map view 销毁后不在处理新接收的位置
			if (location == null)
				return;
			if (isFirstLoc) {
				// isFirstLoc = false;
				// 获取当前位置的经纬度
				LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
				LLogger.e("维度 ： " + location.getLatitude() + "\n" + "经度  : " + location.getLongitude());
				mMapManager.setGeoCoderResultListener(new MyGeoCoderListener());
				mMapManager.reverseLocation(latLng);
			}

		}
		public void onReceivePoi(BDLocation poiLocation) {

		}
	}

	public class MyGeoCoderListener implements OnGetGeoCoderResultListener {

		@Override
		public void onGetGeoCodeResult(GeoCodeResult result) {
			if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
				ToastHelper.toastShort(mContext, "定位失败");
			} else {
				ToastHelper.toastShort(mContext, result.getAddress());
			}
		}

		@Override
		public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {
			if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
				ToastHelper.toastShort(mContext, "定位失败");
			} else {
				AddressComponent component = result.getAddressDetail();
				String mAddress = component.province
						+ component.city + component.district
						+ component.street + component.streetNumber;
				try {
					AreaInfo start = AreaUtils.getAreaInfo(component.province, component.city);
					tvStart.setText(component.province + start.getName());
					startCode = start.getCode();
					PrefUtils.setPrefString(getActivity(), PrefConstants.SRC_PLACE, component.province + start.getName());
					PrefUtils.setPrefString(getActivity(), PrefConstants.SRC_CODE,startCode);
//					ToastHelper.toastShort(mContext, mAddress);
					LContext.mAddress = mAddress;
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.tv_start:
			Intent start = new Intent(mContext, AreaGridActivity.class);
			start.putExtra("title", "始发地");
//			start.putExtra("code", startCode);
			startActivityForResult(start, 500);
			break;
		case R.id.tv_end:
			Intent end = new Intent(mContext, AreaGridActivity.class);
			end.putExtra("title", "目的地");
			startActivityForResult(end, 501);
			break;
		case R.id.btn_search:
			Intent intent=new Intent(mContext, CargoListActivity.class);
			intent.putExtra("startCode", startCode);
			intent.putExtra("endCode", endCode);
			intent.putExtra("srcPlace", tvStart.getText().toString());
			intent.putExtra("destPlace", tvEnd.getText().toString());
			startActivity(intent);
			break;
		case R.id.btn_switch:
			String s = tvEnd.getText().toString();
			String sCode = endCode;
			if(s.contains(",")){
				LLogger.e("larry", s.split(",")[0] + " : " + sCode.split(",")[0]);
				s = s.split(",")[0];
				sCode = sCode.split(",")[0];
			}
			
			String e = tvStart.getText().toString();
			String eCode = startCode;
			startCode = sCode;
			endCode = eCode;
			
			tvStart.setText(s);
			tvEnd.setText(e);
			break;
		case R.id.btn_search_truck:
			Intent truckIntent=new Intent(mContext, SearchTruckListActivity.class);
			truckIntent.putExtra("startCode", startCode);
			truckIntent.putExtra("endCode", endCode);
			truckIntent.putExtra("srcPlace", tvStart.getText().toString());
			truckIntent.putExtra("destPlace", tvEnd.getText().toString());
			startActivity(truckIntent);
			break;

		default:
			break;
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case 500:
			if(data != null){
				try {
					String json = data.getStringExtra("json");
					List<AreaInfo> areas = JsonUtil.getList(json, AreaInfo.class);
					if(areas.size() > 0){
						tvStart.setText(areas.get(0).getName());
						startCode = areas.get(0).getCode();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			break;
		case 501:
			if(data != null){
				try {
					String json = data.getStringExtra("json");
					List<AreaInfo> areas = JsonUtil.getList(json, AreaInfo.class);
					String paddingStr = "";
					endCode = "";
					for(AreaInfo info : areas){
						paddingStr = paddingStr + info.getName() + ",";
						endCode = endCode + info.getCode() + ",";
					}
					if(StringUtil.isNull(paddingStr)){
						tvEnd.setText(paddingStr);
					}else{
						tvEnd.setText(paddingStr.substring(0, paddingStr.length() - 1));
					}
					endCode = endCode.substring(0, endCode.length() - 1);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			break;

		default:
			break;
		}
	}

}
